package com.hyzh.latte.sand.socket.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.coffee.concurrent.CoffeeExecutorManager;
import com.coffee.socketio.CoffeeSocketioException;
import com.coffee.socketio.handler.CoffeeHandler;
import com.coffee.socketio.handler.SocketioJsonHandler;
import com.corundumstudio.socketio.SocketIOClient;
import com.hyzh.latte.sand.SandClient;
import com.hyzh.latte.sand.SandSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.Executor;

/**
 * @author: songkui
 * @since: 2024/3/21 0:14
 */
@CoffeeHandler("SandCommandType.PcRelay")
@Service
@Slf4j
public class PcRelayHandler implements SocketioJsonHandler {

    @Override
    public void handle(String event, SocketIOClient socketIOClient, String json) throws CoffeeSocketioException {
        SandClient client = SandSessionManager.getInstance().getSandClient(socketIOClient.getSessionId().toString());
        if (null != client){
            Set<SandClient> mtList = SandSessionManager.getInstance().getMtList(client.getUserId());
            if (CollectionUtil.isNotEmpty(mtList)){
                Executor executor = CoffeeExecutorManager.getInstance().getDisruptor(client.getUserId().hashCode());
                executor = null == executor ? CoffeeExecutorManager.getInstance().getDefaultExecutor() : executor;
                executor.execute(() -> {
                    for (SandClient c : mtList){
                        c.sendPCMessage(json);
                    }
                });
            }
        }else {
            log.error("PC session  is null [pc session : {} ]", socketIOClient.getSessionId());
        }
    }
}
